import fs from 'fs';
import path from 'path';

export default (
  options = {
    dirs: undefined,
    extensions: undefined
  }
) => {
  const { dirs = ['src/assets/images'], extensions = ['png', 'jpg', 'jpeg', 'svg', 'webp'] } = options;
  const imageRegex = new RegExp(`\\.(${extensions?.join('|')})$`, 'i');
  const images = {};

  const directoryNames = dirs.map((dir) => path.basename(dir));

  // 扫描指定目录下的所有图像文件
  function scanImages(dir) {
    try {
      const files = fs.readdirSync(dir);

      files.forEach((file) => {
        const filePath = path.join(dir, file);
        const stats = fs.statSync(filePath);
        if (stats.isDirectory()) {
          // 递归扫描子目录
          scanImages(filePath);
        } else if (imageRegex.test(file)) {
          const name = file.replace(path.extname(file), '');
          if (images[name]) {
            throw new Error(`Duplicate image filename: "${name}" found in directory "${dir}"`);
          }
          images[name] = filePath;
        }
      });
    } catch (error) {
      console.error(`Error scanning directory ${dir}:`, error);
    }
  }

  // 对每个指定目录进行扫描
  dirs.forEach((dir) => {
    const baseDir = path.resolve(process.cwd(), dir);
    if (fs.existsSync(baseDir)) {
      scanImages(baseDir);
    } else {
      console.warn(`Directory "${baseDir}" does not exist. Skipping...`);
    }
  });

  // 将文件路径转换为文件名 PascalCase
  function url2name(url) {
    for (const dir of directoryNames) {
      const dirIndex = url.indexOf(dir);
      if (dirIndex === -1) continue;
      const part = url.slice(dirIndex + dir.length);
      const segments = part.split('/').filter(Boolean);
      return segments
        .map((v) => v.replace(/\..*$/, '').replace(/(?:^|[-_\s])(\w)/g, (_, x) => x.toUpperCase()))
        .join('');
    }
  }

  // 生成导入语句
  function genImportPath() {
    const imports = [];
    Object.entries(images).forEach(([name, filePath]) => {
      const uPath = path.relative(path.join(process.cwd(), 'src'), filePath).replace(/\\/g, '/');
      const variableName = url2name(uPath) ?? name;
      imports.push(`import ${variableName} from '@/${uPath}';`);
    });
    return imports.join('\n');
  }

  const importStmts = genImportPath();
  return {
    name: 'vite-plugin-images-vue',
    enforce: 'pre',
    // 转换模块内容
    transform(code, id) {
      if (/\.vue$/.test(id)) {
        const scriptMatch = code.match(/<script[^>]*>/);
        if (scriptMatch) {
          const scriptTag = scriptMatch[0];
          const scriptIndex = code.indexOf(scriptTag) + scriptTag.length;
          const newCode = [code.slice(0, scriptIndex), '\n' + importStmts + '\n', code.slice(scriptIndex)].join('');
          return newCode;
        }
      }
      return code;
    }
  };
};
